<template>
  <div class="container">
    <div class="main">
      <div class="header">
        <el-button type="primary" @click="openDialog(null)">新建</el-button>
        <el-button type="success" @click="importData">导入</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <el-select v-model="selectedFilter" @change="handleFilterChange">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <el-input placeholder="请输入关键字搜索" v-model="searchTable" />
        <el-button type="info" @click="query" style="background-color: orange;">查询</el-button>
        <el-button type="info" @click="reset">重置</el-button>
      </div>
      <el-table :empty-text="emptyText" :data="tableData" border class="eltable"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index"  label="序号" width="60"></el-table-column>
        <el-table-column prop="wl_id" v-if="false"></el-table-column>
        <el-table-column prop="wl_code" label="物料编码" width="150"></el-table-column>
        <el-table-column prop="wl_name" label="物料名称" width="290"></el-table-column>
        <el-table-column prop="wl_fl" label="物料分类" width="140" v-if="false"></el-table-column>
        <el-table-column prop="wl_fl_name" label="物料分类"></el-table-column>
        <el-table-column prop="wl_size" label="物料规格"></el-table-column>
        <el-table-column prop="wl_dw" label="物料单位" width="100" v-if="false"></el-table-column>
        <el-table-column prop="wl_dw_name" label="物料单位" width="120"></el-table-column>
        <el-table-column prop="wl_type" label="物料类型" width="120" v-if="false"></el-table-column>
        <el-table-column prop="wl_type_name" label="物料类型" width="120"></el-table-column>
        <el-table-column prop="wl_ly" label="物料来源" width="120" v-if="false"></el-table-column>
        <el-table-column prop="wl_ly_name" label="物料来源" width="120"></el-table-column>
        <el-table-column prop="wl_dj" label="物料单价" width="120"></el-table-column>
        <el-table-column label="启用" width="70">
          <template #default="{ row }">
            <el-switch v-model="row.wl_state" :active-value="1" :inactive-value="0"
              @change="updateState(row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="text" @click="openDialog(row)">编辑</el-button>
            <el-button type="text" @click="deleteRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码：" prop="wl_code">
              <el-input v-model="formData.wl_code"  :readonly="true"  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称：" prop="wl_name">
              <el-input v-model="formData.wl_name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="物料分类：" prop="wl_fl">
              <el-select v-model="formData.wl_fl" placeholder="请选择物料分类">
                <el-option v-for="type in flOptions" :key="type.dictionary_id" :label="type.dictionary_name"
                  :value="type.dictionary_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料规格：" prop="wl_size">
              <el-input v-model="formData.wl_size" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="物料来源：" prop="wl_ly">

              <el-select v-model="formData.wl_ly" placeholder="请选择物料来源">
                <el-option v-for="type in lyOptions" :key="type.dictionary_id" :label="type.dictionary_name"
                  :value="type.dictionary_id" />
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料单位：" prop="wl_dw">
              <el-select v-model="formData.wl_dw" placeholder="请选择物料单位">
                <el-option v-for="type in dwOptions" :key="type.dw_id" :label="type.dw_name" :value="type.dw_id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="20">
          <el-col :span="12">
            <el-form-item label="物料类型：" prop="wl_type">
              <el-select v-model="formData.wl_type" placeholder="请选择物料类型">
                <el-option v-for="type in typeOptions" :key="type.dictionary_id" :label="type.dictionary_name"
                  :value="type.dictionary_id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料单价：" prop="wl_dj">
              <el-input v-model="formData.wl_dj" placeholder="请输入单价" type="number" step="0.01" min="0"
                @keydown.native="handleDecimalInput" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { number } from 'echarts';

export default {
  setup() {
    const emptyText = '暂无数据';
    const selectedFilter = ref('1');
    const searchTable = ref('');
    const tableData = ref([]);
    const multipleSelection = ref([]);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增物料');
    const formRef = ref(null);
    const formData = ref({
      wl_code: '',
      wl_name: '',
      wl_fl: null,
      wl_size: '',
      wl_ly: null,
      wl_dw: null,
      wl_type: null,
      wl_dj: null
    });

    const dwOptions = ref([]);
    const flOptions = ref([]);
    const lyOptions = ref([]);
    const typeOptions = ref([]);

    const formRules = {
      wl_name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
      wl_fl: [{ required: true, message: '请选择物料分类', trigger: 'change' }],
      wl_size: [{ required: true, message: '请输入物料规格', trigger: 'blur' }],
      wl_ly: [{ required: true, message: '请输入物料来源', trigger: 'change' }],
      wl_dw: [{ required: true, message: '请输入选择单位', trigger: 'change' }],
      wl_type: [{ required: true, message: '请选择物料类型', trigger: 'change' }],
      wl_dj: [
        { required: true, message: '请输入物料单价', trigger: 'blur' },
        {
          validator: (_, value, callback) => {
            if (!/^\d+(\.\d{1,2})?$/.test(value)) { // 校验两位小数
              callback(new Error('请输入有效的金额格式（如 10.99）'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ],
    };

    const fetchTableData = () => {
      axios.get(`/api/WL/GetWL?state=${selectedFilter.value}`)
        .then(res => {
          tableData.value = res.data;
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };

    // 选中行变化
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
    };

    // 筛选条件变化
    const handleFilterChange = () => {
      fetchTableData();
    };

    // 更新状态
    const updateState = (row) => {
      ElMessageBox.confirm('改变状态, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/WL/StateChange?id=${row.wl_id}&state=${row.wl_state}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success('状态已更新');
            } else {
              ElMessage.error('更新失败，后端返回错误');
            }
            fetchTableData();
          })
          .catch(err => {
            console.error('Error:', err);
            ElMessage.error('更新失败');
          });
      }).catch(() => {
        fetchTableData();
        ElMessage.info('已取消改变');
      });
    };

    // 查询
    const query = () => {
      searchTableData(); // 假设后端支持关键字搜索，需传递searchTable.value
    };

    const searchTableData = () => {
      if (!searchTable.value) {
        fetchTableData();
        return;
      }
      const params = {
        state: selectedFilter.value,
        str: searchTable.value
      };
      axios.get('/api/WL/GetWL', { params })
        .then(res => {
          tableData.value = res.data;
        })
        .catch(err => {
          console.error('Error fetching data:', err);
          ElMessage.error('加载数据失败，请稍后再试');
        });
    };

    // 重置
    const reset = () => {
      searchTable.value = '';
      selectedFilter.value = '1';
      fetchTableData();
    };

    // 删除单行
    const deleteRow = (row) => {
      ElMessageBox.confirm('此操作将删除该列信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put(`/api/WL/DelWL?id=${row.wl_id}`)
          .then(response => {
            if (response.data === true) {
              ElMessage.success("删除成功");
              fetchTableData();
            } else {
              ElMessage.error("删除失败：后端返回失败");
            }
          })
          .catch(err => {
            console.error('删除失败:', err);
            ElMessage.error("删除失败：请求异常");
          });
      }).catch(() => {
        ElMessage.info("已取消删除");
      });
    };

    const batchDelete = async () => {
      if (multipleSelection.value.length === 0) {
        ElMessage.warning("请先选择要删除的项");
        return;
      }
      try {
        await ElMessageBox.confirm('此操作将删除选中的项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const selectedIds = multipleSelection.value.map(item => item.wl_id); // 确保 wl_id 是后端需要的字段
        const response = await axios.put('/api/WL/DelWLs', selectedIds, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        if (response.data === true) {
          ElMessage.success("批量删除成功");
          fetchTableData();
        } else {
          ElMessage.error("批量删除失败：后端返回失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("批量删除失败");
        } else {
          ElMessage.info("已取消批量删除");
        }
      }
    };

    // 打开弹窗时初始化状态
    const openDialog = async (row) => {
      await Promise.all([fetchWLdw(), fetchWLfl(),fetchWLly(),fetchWLtype()]); // 确保选项加载完成
      dialogVisible.value = true;
      if (row) {
        formData.value = { ...row };
        dialogTitle.value = '编辑物料';
      } else {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let code = `WL${formattedTime}${randomNumber}`;

        dialogTitle.value = '新增物料';
        formData.value = {
          wl_code: code,
          wl_dw: null,
          wl_fl: null,
          wl_ly: null,
          wl_name: '',
          wl_size: '',
          wl_type: null,
          wl_dj: null,

        };
      }
    };
    
    const submitForm = async () => {
  try {
    await formRef.value.validate(); // 表单验证
  } catch (error) {
    ElMessage.warning('请填写完整的表单信息');
    return;
  }

  try {
    // 确保必填字段不为空
    const postData = {
      ...formData.value,
      wl_fl: formData.value.wl_fl || null, // 确保物料分类不为空
      wl_dw: formData.value.wl_dw || null, // 确保物料单位不为空
      wl_ly: formData.value.wl_ly || null, // 默认来源
      wl_type: formData.value.wl_type || null, // 默认类型
      wl_dj: parseFloat(formData.value.wl_dj) || 0 // 转为浮点数
    };

    // 检查必填字段
    if (!postData.wl_fl || !postData.wl_dw || !postData.wl_ly || !postData.wl_type) {
      ElMessage.warning('请填写完整的物料分类、单位、来源和类型');
      return;
    }

    let response;
    if (formData.value.wl_id) {
      response = await axios.put('/api/WL/UpdateWL', postData);
    } else {
      console.log('提交的数据:', postData); // 打印提交的数据，方便调试
      response = await axios.post('/api/WL/AddWL', postData);
    }

    if (response.data === true) {
      ElMessage.success(formData.value.wl_id ? '修改成功' : '新增成功');
      dialogVisible.value = false;
      fetchTableData();
      resetForm();
    } else {
      ElMessage.error('操作失败：' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('操作失败:', error);
    const errorMsg = error.response?.data?.message || error.message;
    ElMessage.error(`操作失败: ${errorMsg}`);
  }
};


    // 获取物料单位
    const fetchWLdw = async () => {
      try {
        const response = await axios.get('/api/DW/GetOneDW');
        dwOptions.value = response.data;
      } catch (error) {
        console.error('获取物料单位失败:', error);
        ElMessage.error('获取物料单位失败，请稍后再试');
      }
    };

    // 获取物料分类
    const fetchWLfl = async () => {
      try {
        const response = await axios.get('/api/Dict/GetOneDict?id=8');
        flOptions.value = response.data; // 正确赋值给flOptions
      } catch (error) {
        console.error('获取物料分类失败:', error);
        ElMessage.error('获取物料分类失败，请稍后再试');
      }
    };

    // 获取物料来源
    const fetchWLly = async () => {
      try {
        const response = await axios.get('/api/Dict/GetOneDict?id=16');
        lyOptions.value = response.data; // 正确赋值给lyOptions
      } catch (error) {
        console.error('获取物料来源失败:', error);
        ElMessage.error('获取物料来源失败，请稍后再试');
      }
    };

    // 获取物料类型
    const fetchWLtype = async () => {
      try {
        const response = await axios.get('/api/Dict/GetOneDict?id=9');
        typeOptions.value = response.data; // 正确赋值给typeOptions
      } catch (error) {
        console.error('获取物料类型失败:', error);
        ElMessage.error('获取物料类型失败，请稍后再试');
      }
    };

    const resetForm = () => {
      formRef.value.resetFields();
    };

    onMounted(() => {
      fetchTableData();
    });

    const handleDecimalInput = (event) => {
      const keysAllowed = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'];
      const keyPressed = event.key;

      // 阻止非法字符输入
      if (!keysAllowed.includes(keyPressed)) {
        event.preventDefault();
        return;
      }

      // 禁止输入多个小数点
      if (keyPressed === '.' && event.target.value.includes('.')) {
        event.preventDefault();
      }
    };

    return {
      searchTableData,
      handleSelectionChange,
      handleFilterChange,
      updateState,
      query,
      reset,
      deleteRow,
      batchDelete,
      emptyText,
      selectedFilter,
      searchTable,
      tableData,
      multipleSelection,
      dialogVisible,
      dialogTitle,
      formRef,
      formData,
      formRules,
      fetchTableData,
      openDialog,
      submitForm,
      resetForm,
      lyOptions,
      typeOptions,
      dwOptions,
      flOptions,
      fetchWLdw,
      fetchWLly,
      fetchWLtype,
      handleDecimalInput
    };
  },
};
</script>

<style scoped>
.container {
  display: flex;
  gap: 20px;
  height: 95%;
}

.sidebar {
  height: 100%;

}

.main {
  width: 80%;
  flex: 1;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.eltable {
  height: 95%;
}

.letree {
  height: 100%;
}

.demo-form-inline .el-input {
  --el-input-width: 200px;
}

.demo-form-inline .el-select {
  --el-select-width: 200px;
}
</style>